package com.zjdiepu.www.biz.yw;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.AuditListStatus;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.CheckEstimateResultStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.MiddleAuditStatus;
import com.zjdiepu.www.base.enums.status.OpenCardStatus;
import com.zjdiepu.www.base.enums.status.PhoneStatus;
import com.zjdiepu.www.base.enums.type.BusinessExtrasCodeType;
import com.zjdiepu.www.base.enums.type.BusinessExtrasType;
import com.zjdiepu.www.base.enums.type.CreditPeopleType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SysParamsType;
import com.zjdiepu.www.base.lang.HttpClientException;
import com.zjdiepu.www.biz.helper.ServiceHelper;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.StringUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessDetailMapper;
import com.zjdiepu.www.dao.base.OtherAttachmentsMapper;
import com.zjdiepu.www.dao.base.SysUserMapper;
import com.zjdiepu.www.dao.dz.DzLoanMiddleAuditMapper;
import com.zjdiepu.www.dao.fk.FkAuditListMapper;
import com.zjdiepu.www.dao.icbc.YwOpenCardHzicbcLogMapper;
import com.zjdiepu.www.dao.icbc.YwOpenCardHzicbcMapper;
import com.zjdiepu.www.dao.other.OtherAuditInfoMapper;
import com.zjdiepu.www.dao.other.OtherTaskAllocationMapper;
import com.zjdiepu.www.dao.system.BaseSalersmanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessBuyerMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarAreaPriceMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessExtrasMapper;
import com.zjdiepu.www.dao.yw.YwBusinessLoanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.dao.zpp.PublicDao;
import com.zjdiepu.www.dao.zx.ZxQueryCreditApplyMapper;
import com.zjdiepu.www.ibiz.fk.IFkAuditListService;
import com.zjdiepu.www.ibiz.other.IOtherFundChannelConfigService;
import com.zjdiepu.www.ibiz.partner.IThYwBusinessRequestService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.ibiz.third.net.IUsedCarExactEstimationService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.zpp.FengKongShenHeService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.ClientTypeExt;
import com.zjdiepu.www.model.base.ext.SysUserExt;
import com.zjdiepu.www.model.base.vo.BusinessTotalVo;
import com.zjdiepu.www.model.dz.dto.DzLoanMiddleAudit;
import com.zjdiepu.www.model.icbc.dto.YwOpenCardHzicbc;
import com.zjdiepu.www.model.icbc.dto.YwOpenCardHzicbcLog;
import com.zjdiepu.www.model.other.dto.OtherAuditInfo;
import com.zjdiepu.www.model.other.dto.OtherFundChannelConfig;
import com.zjdiepu.www.model.other.dto.OtherTaskAllocation;
import com.zjdiepu.www.model.system.dto.BaseSalersman;
import com.zjdiepu.www.model.third.request.juhe.JuheExactEstimationRequest;
import com.zjdiepu.www.model.third.response.juhe.JuheExactEstimationPriceArea;
import com.zjdiepu.www.model.third.response.juhe.JuheExactEstimationResponse;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessCarAreaPrice;
import com.zjdiepu.www.model.yw.dto.YwBusinessExtras;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.ext.YwBusinessBuyerExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarAreaPriceExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessExt;
import com.zjdiepu.www.model.yw.request.ChangeChannelRequest;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.model.zpp.pub.ext.WhereSqlExt;
import com.zjdiepu.www.model.zx.dto.ZxQueryCreditApply;
import com.zjdiepu.www.util.CarHelper;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 业务信息Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月24日 14时45分<br/>
 * @since 1.0<br/>
 */
@Service
public class YwBusinessServiceImpl extends BaseService implements IYwBusinessService {
	
	public static final Logger logger = LoggerFactory.getLogger(YwBusinessServiceImpl.class);

	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private YwBusinessCarAreaPriceMapper ywBusinessCarAreaPriceMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private YwBusinessLoanMapper ywBusinessLoanMapper;
	@Autowired
	private YwBusinessBuyerMapper ywBusinessBuyerMapper;
	@Autowired
	private IFkAuditListService fkAuditListService;
	@Autowired
	private OtherAttachmentsMapper otherAttachmentsMapper;
	@Autowired
	private YwBusinessDetailMapper ywBusinessDetailMapper;
	@Autowired
	private OtherTaskAllocationMapper otherTaskAllocationMapper;
	@Autowired
	private YwBusinessExtrasMapper ywBusinessExtrasMapper;
	@Autowired
	private IBaseSysParamsService baseSysParamsService;
	@Autowired
	private IThYwBusinessRequestService thYwBusinessRequestService;
	@Autowired
	private IUsedCarExactEstimationService<JuheExactEstimationResponse, JuheExactEstimationRequest> juheUsedCarExactEstimationService;
	@Autowired
	private FkAuditListMapper fkAuditListMapper;
	@Autowired
	private BaseSalersmanMapper baseSalersmanMapper;
	@Autowired
	private IOtherFundChannelConfigService otherFundChannelConfigService;
	@Autowired
	private FengKongShenHeService fengKongShenHeService;
	@Autowired
	private ServiceHelper serviceHelper;
	@Autowired
	private DzLoanMiddleAuditMapper dzLoanMiddleAuditMapper;
	@Autowired
	private OtherAuditInfoMapper otherAuditInfoMapper;
	@Autowired
	private ZxQueryCreditApplyMapper zxQueryCreditApplyMapper;
	@Autowired
	private PublicDao publicDao;
	@Autowired
	private YwOpenCardHzicbcMapper ywOpenCardHzicbcMapper;
//	@Autowired
//	private YwOpenCardHzicbcSubmitInfoMapper ywOpenCardHzicbcSubmitInfoMapper;
	@Autowired
	private YwOpenCardHzicbcLogMapper ywOpenCardHzicbcLogMapper;
	
	@Override
	public void updateByExt(YwBusiness ywBusiness, YwBusinessExt ywBusinessExt) {
		if(null == ywBusiness || null == ywBusinessExt) {
			return;
		}
		Map<String, Object> param = CollectionInitUtil.emptyMap();
		param.put("ywBusiness", ywBusiness);
		param.put("ywBusinessExt", ywBusinessExt);
		
		ywBusinessMapper.updateByExtSelective(param);		
	}
	
	@Override
	public void saveChangeChannel(ChangeChannelRequest changeChannelRequest,
			SysUser sysUser) {
		String busiId = changeChannelRequest.getId();
    	
    	YwBusiness ywBusiness = new YwBusiness();
    	ywBusiness.setId(busiId);
    	ywBusiness.setChannelType(changeChannelRequest.getChannelType());
    	String dealerId = changeChannelRequest.getDealerId();
    	ywBusiness.setDealerId(dealerId);
    	ywBusiness.initUpdateData(sysUser.getId(), sysUser.getModifierName());
    	ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
    	
    	String queryCreditApplyId = ywBusiness.getQueryCreditApplyId();
    	if(StringUtils.isNotBlank(queryCreditApplyId)) {
    		ZxQueryCreditApply zxQueryCreditApply = zxQueryCreditApplyMapper.selectByPrimaryKey(queryCreditApplyId);
    		if(null != zxQueryCreditApply) {
    			zxQueryCreditApply.setDealerId(dealerId);
    			zxQueryCreditApplyMapper.updateByPrimaryKeySelective(zxQueryCreditApply);
    		}
    	}
    	
    	Boolean ifPhone = changeChannelRequest.getIfPhone();
    	//判断是否已经保存
		YwBusinessExtras ywBusinessExtras_ = new YwBusinessExtras();
		ywBusinessExtras_.setBusiId(busiId);
		ywBusinessExtras_.setTypeExtras(BusinessExtrasType.PHONE_AUDIT.getCode());
		ywBusinessExtras_.setCodeExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getCode());
		ywBusinessExtras_.setDpStatus(DpStatus.NORMAL.getCode());
		YwBusinessExtras ywBusinessExtrasDb = ywBusinessExtrasMapper.selectRefined(ywBusinessExtras_);
		boolean newYwBusinessExtras = false;
		if(null == ywBusinessExtrasDb) {
			newYwBusinessExtras = true;
			ywBusinessExtrasDb = new YwBusinessExtras();
			ywBusinessExtrasDb.initInsertData(sysUser.getId(), sysUser.getName());
		} else {
			ywBusinessExtrasDb.initUpdateData(sysUser.getId(), sysUser.getName());
		}
		ywBusinessExtrasDb.setBusiId(busiId);
		ywBusinessExtrasDb.setTypeExtras(BusinessExtrasType.PHONE_AUDIT.getCode());
		ywBusinessExtrasDb.setCodeExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getCode());
		ywBusinessExtrasDb.setNameExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getValue());
		ywBusinessExtrasDb.setValueExtras(ifPhone != null && ifPhone ? "1" : "0"); //0：表示不需要电审   1：需要电审
		if(newYwBusinessExtras) {
			ywBusinessExtrasMapper.insert(ywBusinessExtrasDb);
		} else {
			ywBusinessExtrasMapper.updateByPrimaryKeySelective(ywBusinessExtrasDb);
		}
		
	}
	
	@Override
	public void saveRefuseSace(String id, SysUser sysUser) {
		if(StringUtils.isBlank(id)) {
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY);
		}
		YwBusinessDetail ywBusinessDetail = ywBusinessMapper.selectMultiByPrimaryKey(id);
		if (null == ywBusinessDetail) {
			ExceptionHelper.thow("999","业务数据不存在或丢失");
		}
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(id);
		ywBusiness.setBusiStatus(BusiStatus.ZI_LIAO_DENG_JI.getCode());
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		
		OtherAuditInfo otherAuditInfo = new OtherAuditInfo();
		otherAuditInfo.initInsertData(sysUser.getId(), sysUser.getName());
		otherAuditInfo.setModeId(ModeIDType.THDD.getCode());
		otherAuditInfo.setBusiId(id);
		otherAuditInfo.setDataId(id);
		otherAuditInfo.setAuditName("退回订单");
		otherAuditInfo.setAuditStatusValueType("BusiStatus");
		otherAuditInfo.setAuditStatusValue(10);
		otherAuditInfo.setAuditStatus(AuditListStatus.SHEN_PI_TONG_GUO.getCode().toString());
		otherAuditInfo.setAuditDetail("退回订单自动审核");
		otherAuditInfo.setAuditPostil("退回订单自动审核");
		otherAuditInfo.setPreAuditStatusType("BusiStatus");
		otherAuditInfo.setPreAuditStatusValue(ywBusinessDetail.getBusiStatus());
		otherAuditInfo.setPreAuditStatus(AuditListStatus.SHEN_PI_BU_TONG_GUO.getCode().toString());
		otherAuditInfo.setOrgCode(ywBusinessDetail.getOrgCode());
		otherAuditInfo.setOrgName(ywBusinessDetail.getOrgName());
		otherAuditInfoMapper.insert(otherAuditInfo);
	}
	
	@Override
	public void saveComitFinal(String id, SysUser sysUser,String serverRealPath){
		if(StringUtils.isBlank(id)) {
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY);
		}
		YwBusinessDetail ywBusinessDetail = ywBusinessMapper.selectMultiByPrimaryKey(id);
		if (null == ywBusinessDetail) {
			ExceptionHelper.thow("999","业务数据不存在或丢失");
		}
		Date timeApplyOpencard = ywBusinessDetail.getTimeApplyOpencard();
		if(null == timeApplyOpencard) {
			ExceptionHelper.thow("999","需要先完成开卡申请");
		}
		fkAuditListService.insertFkAuditList(ywBusinessDetail, ModeIDType.ZSYS, "资料登记提交终审", sysUser);
		fkAuditListService.insertFkAuditList(ywBusinessDetail, ModeIDType.DSCS, "资料登记提交终审", sysUser);
		
		String loanBank = ywBusinessDetail.getLoanBank();
		//@update 2017-12-14
		String message = "";
		if(!"TJICBC".equals(loanBank)) {
			//鑫合汇借款申请 2017-09-28
			String fundChannel = "xhh";
			Double realLoanAmount = ywBusinessDetail.getRealLoanAmount();
			String salesmanId = ywBusinessDetail.getSalesmanId();
			if(StringUtils.isNotBlank(salesmanId)) {
				BaseSalersman baseSalersman = baseSalersmanMapper.selectByPrimaryKey(salesmanId);
				if(null != baseSalersman) {
					String unitCode = baseSalersman.getUnitCode();
					List<OtherFundChannelConfig> otherFundChannelConfigs = otherFundChannelConfigService.getOtherFundChannelConfigByUnitCode(unitCode, fundChannel);
					if(CollectionUtils.isNotEmpty(otherFundChannelConfigs)) {
						OtherFundChannelConfig otherFundChannelConfig = otherFundChannelConfigs.get(0);
						Double realLoanAmountConfig = otherFundChannelConfig.getRealLoanAmount();
						if(realLoanAmountConfig != null && realLoanAmount <= realLoanAmountConfig){
							boolean saveApplyXinHeHuiLoan = thYwBusinessRequestService.saveApplyXinHeHuiLoan(id, sysUser.getId(),sysUser.getName());
							if(saveApplyXinHeHuiLoan) {
								message = "发送鑫合汇成功";
							} else {
								message = "配置检查成功,但发送鑫合汇失败";
							}
						}  else {
							message = "地区配置不存在或不符合,应该小于:" + (otherFundChannelConfig != null ? otherFundChannelConfig.getRealLoanAmount() : 0) + ",实际为:" + realLoanAmount;
						}
					} else {
						message = "业务单位所在地区配置不存在,业务单位编码:" + unitCode;
					}
				} else {
					message = "没有查询到对应业务员,业务员ID:" + salesmanId;
				}
			} else {
				message = "业务员ID为空";
			}
		} else {
			message = "天津工行不发送鑫合汇,银行:" + loanBank;
		}
		String uuid = UUIDFactory.getUUID();
		String sqlXmls = "INSERT INTO `sys_log4j`(`id`,`logName`,`userName`,`logClass`,`mothod`,`createTime`,`logLevel`,`message`)"
				+ " VALUES ('" + uuid + "', '鑫合汇借款申请', '"+ sysUser.getName() +"', '"+ ywBusinessDetail.getId()+"','YwBusinessServiceImpl.saveComitFinal', '"+DateUtil.dateTo14String(new Date())+"', 'info','" + message + "')";
    	WhereSqlExt whereSqlExt = new WhereSqlExt();
    	whereSqlExt.setWhereSql(sqlXmls);
    	publicDao.insertWhereSql(whereSqlExt);
		
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(id);
		ywBusiness.setBusiStatus(BusiStatus.ZI_SHEN_YI_SHEN_ZHONG.getCode());
		ywBusiness.setPhoneStatus(PhoneStatus.PHONE_1_ING.getCode());
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		try 
		{
			//自动审核  资审一审 电审一审
			String[] modeId = {ModeIDType.ZSYS.getCode(),ModeIDType.DSCS.getCode()};
			fengKongShenHeService.diepuZiDongShenWaiBu(sysUser,modeId,ywBusiness.getId(),serverRealPath);
		} 
		catch (Exception e) 
		{
			
			logger.error(e.getMessage());
		}
		finally
		{
			logger.debug("自动审核执行完毕");
		}
	}
	
	@Override
	public List<YwBusiness> selectByCustomerNo(String customerNo) {
		return ywBusinessMapper.selectByCustomerNo(customerNo);
	}
	@Override
	public void updateForApplyAllocation(int allocationNum, SysUser sysUser) {
		YwBusinessExt ywBusinessExt = new YwBusinessExt();
    	ywBusinessExt.setBaseWhere();
		ywBusinessExt.withOutPage();
		ywBusinessExt.addBusiStatus(BusiStatus.ZI_LIAO_DENG_JI.getCode());
		ywBusinessExt.setCodeUnits(sysUser.getCodeUnits());
        List<YwBusiness> ywBusinesss = ywBusinessMapper.selectNotAllocation(ywBusinessExt);
        
        Random random = new Random();
        int ywBusinessCounts = ywBusinesss.size();
        List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
		for(int i = 0; i < allocationNum && ywBusinessCounts > 0; i++) {
        	int nextBusinessInt = random.nextInt(ywBusinessCounts);
        	YwBusiness randomYwBussiness = ywBusinesss.get(nextBusinessInt);
        	randomYwBussiness.initUpdateData(sysUser.getId(), sysUser.getName());
        	randomYwBussiness.setOperatorId(sysUser.getId());
        	randomYwBussiness.setOperatorName(sysUser.getUname());
        	randomYwBussiness.setAcceptDate(new Date());
        	
        	ywBusinesss.remove(randomYwBussiness);
        	ywBusinessCounts--;
        	
        	OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
    		otherTaskAllocation.initInsertData(sysUser.getId(), sysUser.getName());
    		otherTaskAllocation.setModeId(ModeIDType.ZLDJ.getCode());
    		otherTaskAllocation.setDataid(randomYwBussiness.getId());
    		otherTaskAllocation.setAlloterId(sysUser.getId());
    		otherTaskAllocation.setAlloterName(sysUser.getName());
    		otherTaskAllocation.setReceiverId(sysUser.getId());
    		otherTaskAllocation.setReceiverName(sysUser.getUname());
    		otherTaskAllocations.add(otherTaskAllocation);
        	
        	ywBusinessMapper.updateByPrimaryKeySelective(randomYwBussiness);
		}
		
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
		
	}
	
	@Override
	public ApiResponse saveAllocation(String id, String operatorId,
			String operatorName, AbstractSysUser currentUser) {
		YwBusiness ywBusiness = new YwBusiness();
		String userId = currentUser.getId();
		String userName=  currentUser.getName();
    	ywBusiness.initUpdateData(userId, userName);
    	ywBusiness.setOperatorId(operatorId);
    	ywBusiness.setOperatorName(operatorName);
    	ywBusiness.setAcceptDate(new Date());
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessMapper.updateCommonBatch(ywBusiness, ids);
    	List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
    	for(String id_ : ids) {
    		OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
    		otherTaskAllocation.initInsertData(userId, userName);
    		otherTaskAllocation.setModeId(ModeIDType.ZLDJ.getCode());
    		otherTaskAllocation.setDataid(id_.trim());
    		otherTaskAllocation.setAlloterId(currentUser.getId());
    		otherTaskAllocation.setAlloterName(currentUser.getName());
    		otherTaskAllocation.setReceiverId(operatorId);
    		otherTaskAllocation.setReceiverName(operatorName);
    		otherTaskAllocations.add(otherTaskAllocation);
    	}
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
    	return ApiResponse.success(true);
	}
	
	//随机数
    private static final Random random = new Random();
    
	@Override
	public void updateForRandomAllocation(int allocationNum, SysUser sysUser) {
    	String orgId = sysUser.getOrgId();
    	SysUserExt sysUserExt = new SysUserExt();
    	sysUserExt.setBaseWhere();
    	sysUserExt.withOutPage();
    	sysUserExt.setOrgId(orgId);
    	List<SysUser> sysUsers = sysUserMapper.selectByExt(sysUserExt);
    	int userCounts = sysUsers.size();
    	
    	YwBusinessExt ywBusinessExt = new YwBusinessExt();
    	ywBusinessExt.setBaseWhere();
		ywBusinessExt.withOutPage();
		ywBusinessExt.addBusiStatus(BusiStatus.ZI_LIAO_DENG_JI.getCode());
		ywBusinessExt.setCodeUnits(sysUser.getCodeUnits());
        List<YwBusiness> ywBusinesss = ywBusinessMapper.selectNotAllocation(ywBusinessExt);
        int ywBusinessCounts = ywBusinesss.size();
        List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
    	if(userCounts > 0) {
    		for(int i = 0; i < allocationNum && ywBusinessCounts > 0; i++) {
	    		int nextUserIndex = random.nextInt(userCounts);
	    		SysUser randomUser = sysUsers.get(nextUserIndex);
	        	int nextBusinessInt = random.nextInt(ywBusinessCounts);
	        	YwBusiness randomYwBusiness = ywBusinesss.get(nextBusinessInt);
	        	randomYwBusiness.initUpdateData(sysUser.getId(), sysUser.getName());
	        	randomYwBusiness.setOperatorId(randomUser.getId());
	        	randomYwBusiness.setOperatorName(randomUser.getUname());
	        	randomYwBusiness.setAcceptDate(new Date());
	        	
	        	ywBusinesss.remove(randomYwBusiness);
	        	ywBusinessCounts--;
	        	
	        	OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
	    		otherTaskAllocation.initInsertData(sysUser.getId(), sysUser.getName());
	    		otherTaskAllocation.setModeId(ModeIDType.ZLDJ.getCode());
	    		otherTaskAllocation.setDataid(randomYwBusiness.getId());
	    		otherTaskAllocation.setAlloterId(sysUser.getId());
	    		otherTaskAllocation.setAlloterName(sysUser.getName());
	    		otherTaskAllocation.setReceiverId(randomUser.getId());
	    		otherTaskAllocation.setReceiverName(randomUser.getUname());
	    		otherTaskAllocations.add(otherTaskAllocation);
	        	
	        	ywBusinessMapper.updateByPrimaryKeySelective(randomYwBusiness);
    		}
    	}
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
	}
	
	@Override
	public String queryHistoryByCustomerNo(String customerNo) {
		if(StringUtils.isBlank(customerNo)){
			return StringUtil.EMPTY;
		}
		return ywBusinessMapper.queryHistoryByCustomerNo(customerNo);
	}
	
	@Override
	public void saveUpdateAndDelete(YwBusiness ywBusiness, OperateType operType) {
		switch (operType) {
		case add:
			ywBusiness.initInsertData(ywBusiness.getModifier(), ywBusiness.getModifierName());
			ywBusinessMapper.insert(ywBusiness);
			break;
		case edit:
			ywBusiness.initUpdateData(ywBusiness.getModifier(), ywBusiness.getModifierName());
			// 影响的记录数
			int updateCount = ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			ywBusiness.initDeleteData(ywBusiness.getModifier(), ywBusiness.getModifierName());
			// 影响的记录数
			int deleteCount = ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<YwBusiness> selectByExt(YwBusinessExt ywBusinessExt) {
		return ywBusinessMapper.selectByExt(ywBusinessExt);
	}
	
	@Override
	public int countByExt(YwBusinessExt ywBusinessExt){
		return ywBusinessMapper.countByExt(ywBusinessExt);
	}
	
	@Override
	public YwBusiness selectById(String id) {
		return ywBusinessMapper.selectByPrimaryKey(id);
	}
	

	@Override
	public YwBusinessDetail getMultiById(String id) {
		return  ywBusinessMapper.selectMultiByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			ywBusinessMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(YwBusiness ywBusiness) {
		return ywBusinessMapper.countRefined(ywBusiness);
	}

	@Override
	public YwBusiness selectRefined(YwBusiness ywBusiness) {
		return ywBusinessMapper.selectRefined(ywBusiness);
	}

	@Override
	public boolean repeat(YwBusiness ywBusiness) {
		int count = countRefined(ywBusiness);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(ywBusiness.getId())) {
			return true;
		}
		YwBusiness dbItem = selectRefined(ywBusiness);
		if(null == dbItem) {
			return false;
		}
		return !ywBusiness.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return ywBusinessMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}

	@Override
	public List<YwBusiness> selectMultiByExt(
			YwBusinessQueryRequest ywBusinessQueryRequest) {
		return ywBusinessMapper.selectMultiByExt(ywBusinessQueryRequest);
	}

	@Override
	public int countMultiByExt(YwBusinessQueryRequest ywBusinessQueryRequest) {
		return ywBusinessMapper.countMultiByExt(ywBusinessQueryRequest);
	}

	@Override
	@Transactional(readOnly=false, isolation=Isolation.READ_COMMITTED, propagation=Propagation.REQUIRED)
	public ApiResponse saveYwBusinessCarAreaPrice(JuheExactEstimationRequest request, AbstractSysUser currentUser) {
		try {
			CheckEstimateResultStatus checkIfNeedEstimate = checkIfNeedEstimate(request);
			if(CheckEstimateResultStatus.YI_GU_JIA.equals(checkIfNeedEstimate)) {
				return ApiResponse.fail(ResultFlagType.ESTIMATE_REPEAT);
			}
	  		if(CheckEstimateResultStatus.CHONG_XIN_GU_JIA.equals(checkIfNeedEstimate)) {
	  			YwBusinessCarAreaPrice ywBusinessCarAreaPrice = new YwBusinessCarAreaPrice();
	  			ywBusinessCarAreaPrice.setBusiId(request.getBusiId());
	  			ywBusinessCarAreaPrice.setCarId(request.getCarId());
	  			ywBusinessCarAreaPriceMapper.deletedRefined(ywBusinessCarAreaPrice);
	  		}
	  		
	  		List<YwBusinessCarAreaPrice> ywBusinessCarAreaPrices = new ArrayList<YwBusinessCarAreaPrice>();
	  		JuheExactEstimationResponse exactEstimation = juheUsedCarExactEstimationService.exactEstimation(request);
			if(null != exactEstimation) {
				List<JuheExactEstimationPriceArea> estPriceAreas = exactEstimation.getEstPriceArea();
				if(CollectionUtils.isNotEmpty(estPriceAreas)) {
					for(JuheExactEstimationPriceArea estPriceArea : estPriceAreas){
						YwBusinessCarAreaPrice ywBusinessCarAreaPrice = new YwBusinessCarAreaPrice();
						ywBusinessCarAreaPrice.initInsertData(currentUser.getId(), currentUser.getName());
						ywBusinessCarAreaPrice.setBusiId(request.getBusiId());
						ywBusinessCarAreaPrice.setCarId(request.getCarId());
						ywBusinessCarAreaPrice.setAreaId(estPriceArea.getAreaId());
						ywBusinessCarAreaPrice.setAreaName(estPriceArea.getArea());
						ywBusinessCarAreaPrice.setPrice(estPriceArea.getPrice());
						ywBusinessCarAreaPrices.add(ywBusinessCarAreaPrice);
					}
					ywBusinessCarAreaPriceMapper.insertBatch(ywBusinessCarAreaPrices);
					YwBusinessCar ywBusinessCar = new YwBusinessCar();
					ywBusinessCar.setId(request.getCarId());
					ywBusinessCar.setCarStatus(String.valueOf(request.getCarStatus()));
					ywBusinessCar.setCarPurpose(String.valueOf(request.getPurpose()));
					ywBusinessCar.setCarStatus(String.valueOf(request.getCarStatus()));
					ywBusinessCar.setEvaluateProvince(String.valueOf(request.getProvince()));
					ywBusinessCar.setEvaluateCity(String.valueOf(request.getCity()));
					ywBusinessCar.setCarBrand(String.valueOf(request.getBrand()));
					ywBusinessCar.setCarSeries(String.valueOf(request.getSeries()));
					ywBusinessCar.setCarModel(String.valueOf(request.getCar()));
					ywBusinessCar.setStartYear(request.getUsedDate());
					ywBusinessCar.setStartMonth(Integer.valueOf(request.getUsedDateMonth()));
					ywBusinessCar.setMileage(request.getMileage());
					ywBusinessCar.setPrice(request.getPrice() == null ? 0 : request.getPrice() * 10000);
					ywBusinessCarMapper.updateByPrimaryKeySelective(ywBusinessCar);
				}
			}
			return ApiResponse.success(ywBusinessCarAreaPrices);
		} catch (SocketTimeoutException | HttpClientException e) {
			//try n times again .
			return ApiResponse.fail(ResultFlagType.FAIL.getCode(), "请求估价服务发生异常!");
		}
	}

	@Override
	public CheckEstimateResultStatus checkIfNeedEstimate(JuheExactEstimationRequest request) {
		YwBusinessCarAreaPriceExt ywBusinessCarAreaPriceExt = new YwBusinessCarAreaPriceExt();
  		ywBusinessCarAreaPriceExt.setBusiId(request.getBusiId());
  		ywBusinessCarAreaPriceExt.setCarId(request.getCarId());
  		ywBusinessCarAreaPriceExt.setBaseWhere();
  		int count = ywBusinessCarAreaPriceMapper.countByExt(ywBusinessCarAreaPriceExt);
  		if(count > 0){ //有估价记录
  			YwBusinessCar oldYwBusinessCar = ywBusinessCarMapper.selectByPrimaryKey(request.getCarId());
  			if(CarHelper.hasEstimate(request, oldYwBusinessCar)){ //已经估价，且条件一致
  				return CheckEstimateResultStatus.YI_GU_JIA;
  			} else { //重新估价
  				return CheckEstimateResultStatus.CHONG_XIN_GU_JIA;
  			}
  		} else { //没有估价
  			return CheckEstimateResultStatus.WEI_GU_JIA; 
  		}
	}

	@Override
	public int countNotAllocation(YwBusinessExt ywBusinessExt) {
		return ywBusinessMapper.countNotAllocation(ywBusinessExt);
	}

	@Override
	public List<YwBusiness> selectNotAllocation(YwBusinessExt ywBusinessExt) {
		return ywBusinessMapper.selectNotAllocation(ywBusinessExt);
	}

	@Override
	public int updateCommonBatch(YwBusiness ywBusiness, List<String> ids) {
		return ywBusinessMapper.updateCommonBatch(ywBusiness, ids);
	}


	@Override
	public List<YwBusiness> selectLessOptionsByExt(
			YwBusinessQueryRequest ywBusinessQueryRequest) {
		return ywBusinessMapper.selectLessOptionsByExt(ywBusinessQueryRequest);
	}

	@Override
	public int countLessOptionsByExt(
			YwBusinessQueryRequest ywBusinessQueryRequest) {
		return ywBusinessMapper.countLessOptionsByExt(ywBusinessQueryRequest);
	}
	/**
	 * @return 0.数据完整  1.业务数据信息不完整 2.购车人信息不完整 3.车辆信息不完整 4.车贷信息不完整<br/>
	 *          5.身份证明资料不足 6.必须上传结婚证或单身结局证之一 7.重要原件资料不足  8.配偶签字资料不足<br/>
	 *          9.居住证明资料不足 10.银行流水资料不足 11.主借人签字资料不足 12.只能上传结婚证或单身结局证之一<br/>
	 */
	@Override
	public ApiResponse saveCompleted(String id, AbstractSysUser currentUser, boolean ifPhone, String channelType) {
		//业务详情
		YwBusinessDetail ywBusinessDetail = ywBusinessMapper.selectMultiByPrimaryKey(id);
		if (null == ywBusinessDetail) {
			return ApiResponse.fail(1,"业务记录丢失或已被删除");
		}
		
		if(!ywBusinessDetail.isCompleted()) {
			return ApiResponse.fail(1,"业务数据不完整");
		}

		// 查询车辆
		YwBusinessCar ywBusinessCar = new YwBusinessCar();
		ywBusinessCar.setDpStatus(DpStatus.NORMAL.getCode());
		ywBusinessCar.setBusiId(id);
		ywBusinessCar = ywBusinessCarMapper.selectRefined(ywBusinessCar);
		if(null == ywBusinessCar) {
			return ApiResponse.fail(3,"车辆信息不完整，请检查");
		}
		if(!ywBusinessCar.isCompleted()) {
			return ApiResponse.fail(3,"车辆信息不完整");
		}
		
		// 车贷信息
		YwBusinessLoan ywBusinessLoan = new YwBusinessLoan();
		ywBusinessLoan.setDpStatus(DpStatus.NORMAL.getCode());
		ywBusinessLoan.setBusiId(id);
		ywBusinessLoan = ywBusinessLoanMapper.selectRefined(ywBusinessLoan);
		if(null == ywBusinessLoan) {
			return ApiResponse.fail(4,"车贷信息不完整，请检查");
		}
		ywBusinessLoan.setCarType(ywBusinessCar.getCarType());
		if(!ywBusinessLoan.isCompleted()) {
			return ApiResponse.fail(4,"车贷信息不完整");
		}
		
		// 查询购车人信息
		YwBusinessBuyer ywBusinessBuyerParam = new YwBusinessBuyer();
		ywBusinessBuyerParam.setDpStatus(DpStatus.NORMAL.getCode());
		ywBusinessBuyerParam.setBusiId(id);
		ywBusinessBuyerParam.setCarManType("03");
		YwBusinessBuyer ywBusinessBuyer = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyerParam);
		if(null == ywBusinessBuyer) {
			return ApiResponse.fail(2,"购车人【" + ywBusinessDetail.getCustomerName() + "】记录丢失");
		}
		if(!ywBusinessBuyer.isCompleted()) {
			return ApiResponse.fail(2,"购车人【" + ywBusinessBuyer.getName() + "】信息不完整");
		}
		
		ywBusinessBuyerParam.setCarManType("01");
		ywBusinessBuyer = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyerParam);
		if(null != ywBusinessBuyer) {//有共同购车人时判断信息是否完整
			if(!ywBusinessBuyer.isCompleted()) {
				return ApiResponse.fail(17,"共同购车人【" + ywBusinessBuyer.getName()+ "】信息不完整");
			}
		}
		
		YwBusinessBuyerExt ywBusinessBuyerExt = new YwBusinessBuyerExt();
		ywBusinessBuyerExt.setBaseWhere();
		ywBusinessBuyerExt.setBusiId(id);
		ywBusinessBuyerExt.setCarManType("02");
		List<YwBusinessBuyer> ywBusinessDbBuyers = ywBusinessBuyerMapper.selectByExt(ywBusinessBuyerExt);
		if(CollectionUtils.isNotEmpty(ywBusinessDbBuyers)) {//有共同购车人时判断信息是否完整
			for(YwBusinessBuyer ywBusinessDanbaorenBuyer : ywBusinessDbBuyers) {
				if(!ywBusinessDanbaorenBuyer.isCompleted()) {
					return ApiResponse.fail(17,"担保人【" +ywBusinessDanbaorenBuyer.getName()+ "】信息不完整");
				}
			}
		}
		
		//附件资料
//		OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
//		otherAttachmentsExt.setBaseWhere();
//		otherAttachmentsExt.withOutPage();
//		otherAttachmentsExt.setDataid(ywBusinessDetail.getQueryCreditApplyId());// 所属业务
//		otherAttachmentsExt.setModeId(ModeIDType.ZXCX.getCode()); // 所处阶段 ZXCX和ZLDJ
//		otherAttachmentsExt.setCustomerId(null);
//		int count111 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		if(count111 < 3) {
//			return ApiResponse.fail(11,"身份证明资料不足"); //请上传征信授权Word
//		}
//		otherAttachmentsExt.setDataid(id);
//		otherAttachmentsExt.setModeId(ModeIDType.ZLDJ.getCode());
//		otherAttachmentsExt.setCustomerId(ywBusinessDetail.getCustomerId());// 所属客户
//		otherAttachmentsExt.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//		int count2 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		otherAttachmentsExt.setFileLabel(AttachmentLabel.JIE_HUN_ZHENG.getCode());
//		int count3 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		otherAttachmentsExt.setFileLabel(AttachmentLabel.DAN_SHEN_JU_JIE_SHU.getCode());
//		int count4 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		otherAttachmentsExt.setFileLabel(null);
//		if(count3 == 0 && count4 == 0) {
//			return ApiResponse.fail(6,"必须上传结婚证或单身结局证之一 "); //必须上传之一
//		} else if (count3 != 0  && count4 != 0) {
//			return ApiResponse.fail(12,"只能上传结婚证或单身结局证之一"); //只能上传之一
//		} else if(count3 != 0){
//			if(count2 < 7) {
//				return ApiResponse.fail(7,"重要原件资料不足"); //重要原件资料不足
//			}
//			otherAttachmentsExt.setAttachmentSort(AttachmentSort.PEI_OU_QIAN_ZI.getCode());
//			int count8 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//			if(count8 < 3) {
//				return ApiResponse.fail(8,"配偶签字资料不足"); //配偶签字资料不足
//			}
//		} else {
//			if(count2 < 6) {
//				return ApiResponse.fail(7,"重要原件资料不足"); //重要原件资料不足
//			}
//		}
		
//		otherAttachmentsExt.setAttachmentSort(AttachmentSort.JU_ZHU_ZHENG_MING.getCode());
//		int count5 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		if(count5 < 1) {
//			return ApiResponse.fail(9,"请上传居住证明资料"); //居住证明资料不足
//		}
//		
//		otherAttachmentsExt.setAttachmentSort(AttachmentSort.YIN_HANG_LIU_SHUI.getCode());
//		int count6 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		if(count6 < 1) {
//			return ApiResponse.fail(10,"请上传银行流水资料"); //银行流水资料不足
//		}
//		
//		otherAttachmentsExt.setAttachmentSort(AttachmentSort.ZHU_JIE_REN_QIAN_ZI.getCode());
//		int count7 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		if(count7 < 3) {
//			return ApiResponse.fail(11,"主借人签字资料不足"); //主借人签字资料不足
//		}
//		
//		otherAttachmentsExt.setAttachmentSort(AttachmentSort.KAI_KA_ZI_LIAO.getCode());
//		int count9 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		if(count9 < 2) {
//			return ApiResponse.fail(13,"开卡资料不足"); //开卡资料不足
//		}
//		
//		otherAttachmentsExt.setAttachmentSort(AttachmentSort.JIA_FANG.getCode());
//		int count10 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//		if(count10 < 1) {
//			return ApiResponse.fail(14,"请上传家访资料"); //家访资料
//		}
		
//		String licencePlateType = ywBusinessCar.getLicencePlateType();
//		if("02".equals(licencePlateType)){ //公牌
//			otherAttachmentsExt.setAttachmentSort(AttachmentSort.DAN_WEI_FANG.getCode());
//			int count11 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
//			if(count11 < 1) {
//				return ApiResponse.fail(15,"请上传单位访资料"); //单位访资料
//			}
//		}
		
		/*otherAttachmentsExt.setAttachmentSort(AttachmentSort.TI_CHE_ZI_LIAO.getCode());
		int count12 = otherAttachmentsMapper.countByExt(otherAttachmentsExt);
		if(count12 < 1) {
			return ApiResponse.fail(16,"请上传提车资料"); //提车资料
		}*/
		
		if(StringUtils.isNotBlank(channelType)) {
			ywBusinessDetail.setChannelType(channelType);
		}
		
		if("30".equals(ywBusinessDetail.getChannelType())) { //二证贷
			String loanBank = ywBusinessLoan.getLoanBank();
			if(!"ICBC".equals(loanBank)) {
				return ApiResponse.fail(999, "非工商银行不能选择二证贷");
			}
			Double realLoanAmount = ywBusinessDetail.getRealLoanAmount();
			//允许二证贷的贷款金额
			Double twoPapersAmount = (Double)SysParamsType.TWO_PAPERS_AMOUNT.getDefaultValue();
			String paramValue = baseSysParamsService.getValueByCode(SysParamsType.TWO_PAPERS_AMOUNT.getCode());
			if(StringUtils.isNotBlank(paramValue)) {
				twoPapersAmount = Double.parseDouble(paramValue);
			}
			if(realLoanAmount > twoPapersAmount) {
				return ApiResponse.fail(999, "金额大于"+ twoPapersAmount + "不能选择二证贷");
			}
			
			//判断是否已经保存
			YwBusinessExtras ywBusinessExtras_ = new YwBusinessExtras();
			ywBusinessExtras_.setBusiId(ywBusinessDetail.getId());
			ywBusinessExtras_.setTypeExtras(BusinessExtrasType.PHONE_AUDIT.getCode());
			ywBusinessExtras_.setCodeExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getCode());
			ywBusinessExtras_.setDpStatus(DpStatus.NORMAL.getCode());
			YwBusinessExtras ywBusinessExtrasDb = ywBusinessExtrasMapper.selectRefined(ywBusinessExtras_);
			boolean newYwBusinessExtras = false;
			if(null == ywBusinessExtrasDb) {
				newYwBusinessExtras = true;
				ywBusinessExtrasDb = new YwBusinessExtras();
				ywBusinessExtrasDb.initInsertData(currentUser.getId(), currentUser.getName());
			} else {
				ywBusinessExtrasDb.initUpdateData(currentUser.getId(), currentUser.getName());
			}
			ywBusinessExtrasDb.setBusiId(ywBusinessDetail.getId());
			ywBusinessExtrasDb.setTypeExtras(BusinessExtrasType.PHONE_AUDIT.getCode());
			ywBusinessExtrasDb.setCodeExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getCode());
			ywBusinessExtrasDb.setNameExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getValue());
			ywBusinessExtrasDb.setValueExtras(ifPhone ? "1" : "0"); //0：表示不需要电审   1：需要电审
			if(newYwBusinessExtras) {
				ywBusinessExtrasMapper.insert(ywBusinessExtrasDb);
			} else {
				ywBusinessExtrasMapper.updateByPrimaryKeySelective(ywBusinessExtrasDb);
			}
		} else {
			//非二证贷，删除电审状态
			YwBusinessExtras ywBusinessExtras = new YwBusinessExtras();
			ywBusinessExtras.setBusiId(ywBusinessDetail.getId());
			ywBusinessExtras.setTypeExtras(BusinessExtrasType.PHONE_AUDIT.getCode());
			ywBusinessExtras.setCodeExtras(BusinessExtrasCodeType.IS_PHONE_AUDIT.getCode());
			ywBusinessExtras.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessExtrasMapper.deletedRefined(ywBusinessExtras);
		}
		
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(id);
		ywBusiness.setChannelType(channelType);
		ywBusiness.setBusiStatus(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_ZHONG.getCode());
//		业务提交时间为征信录入生成订单时间
//		ywBusiness.setSubmitTime(new Date());
		ywBusiness.setBankLoan(ywBusinessLoan.getLoanBank());
		ywBusiness.setRealLoanAmount(ywBusinessLoan.getLoanAmount());
		ywBusiness.setSignLoanAmount(ywBusinessLoan.getSignLoanAmount());
		ywBusiness.setCarType(ywBusinessCar.getCarType());
		
		fkAuditListService.insertFkAuditList(ywBusinessDetail, ModeIDType.CSDCS, "资料登记", currentUser);
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		return ApiResponse.success(true);
	}
	
	@Override
	public void updateRefundStatus(YwBusinessExt ywExt) {
		
		ywBusinessMapper.updateRefundStatus(ywExt);
	}

	@Override
	public void modifyAll(YwBusiness ywBusiness, AbstractSysUser currentUser) {
		YwBusiness ywBusiness1=ywBusinessMapper.selectByPrimaryKey(ywBusiness.getId());
		ywBusiness1.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
		ywBusiness1.setModifierName(currentUser.getName());
		ywBusiness1.setTimeApplyOpencard(ywBusiness.getTimeApplyOpencard());
    	ywBusiness1.initUpdateData(ywBusiness1.getModifier(), ywBusiness1.getModifierName());
		// 影响的记录数
		int updateCount = ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness1);
		if(updateCount == 0){
			throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
		} else if(updateCount > 1){
			throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
		}
    	
    	
    	//插入贷中信息风控数据
		DzLoanMiddleAudit dzLoanMiddleAudit1=new DzLoanMiddleAudit();
		dzLoanMiddleAudit1.setBusiId(ywBusiness.getId());
		dzLoanMiddleAudit1=dzLoanMiddleAuditMapper.selectRefined(dzLoanMiddleAudit1);
		if(dzLoanMiddleAudit1!=null){
			dzLoanMiddleAudit1.setBusiId(ywBusiness.getId());
			dzLoanMiddleAudit1.setCusId(ywBusiness.getCustomerId());
			dzLoanMiddleAudit1.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
			dzLoanMiddleAudit1.setModifierName(currentUser.getName());
			dzLoanMiddleAudit1.setTimeApplyOpencard(ywBusiness.getTimeApplyOpencard());
			dzLoanMiddleAudit1.setMiddleAuditStatus(MiddleAuditStatus.WEI_TI_JIAO.getCode());
			dzLoanMiddleAudit1.initUpdateData(ywBusiness.getModifier(), ywBusiness.getModifierName());
			// 影响的记录数
			int updateCount1 = dzLoanMiddleAuditMapper.updateByPrimaryKeySelective(dzLoanMiddleAudit1);
			if(updateCount1 == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount1 > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
		}else{
			DzLoanMiddleAudit dzLoanMiddleAudit=new DzLoanMiddleAudit();
			dzLoanMiddleAudit.setBusiId(ywBusiness.getId());
			dzLoanMiddleAudit.setCusId(ywBusiness.getCustomerId());
			dzLoanMiddleAudit.setTimeApplyOpencard(ywBusiness.getTimeApplyOpencard());
			dzLoanMiddleAudit.setMiddleAuditStatus(MiddleAuditStatus.WEI_TI_JIAO.getCode());
			dzLoanMiddleAudit.initInsertData(ywBusiness.getModifier(), ywBusiness.getModifierName());
			dzLoanMiddleAuditMapper.insert(dzLoanMiddleAudit);
		}
    	
    	YwBusinessBuyer ywBusinessBuyer= new YwBusinessBuyer();
    	ywBusinessBuyer.setBusiId(ywBusiness.getId());
    	ywBusinessBuyer.setCarManType(CreditPeopleType.ZHU_JIE_REN.getCode());
    	YwBusinessBuyer ywBuyer=ywBusinessBuyerMapper.selectRefined(ywBusinessBuyer);
    	if(ywBuyer!=null){
    		ywBuyer.setRemarkOpenCard(ywBusiness.getRemark());
    		ywBuyer.initUpdateData(ywBusiness.getModifier(), ywBusiness.getModifierName());
			// 影响的记录数
			int updateCount1 = ywBusinessBuyerMapper.updateByPrimaryKeySelective(ywBuyer);
			if(updateCount1 == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount1 > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
    	}
		
	}

	@Override
	public int countBusinessNum(ClientTypeExt clientTypeExt) {
		return ywBusinessMapper.countBusinessNum(clientTypeExt);
	}

	@Override
	public List<BusinessTotalVo> selectBusinessNum(ClientTypeExt clientTypeExt) {
		return ywBusinessMapper.selectBusinessNum(clientTypeExt);
	}

	@Override
	public int countXHHNum(ClientTypeExt clientTypeExt) {
		return ywBusinessMapper.countXHHNum(clientTypeExt);
	}

	@Override
	public List<BusinessTotalVo> selectXHHNum(ClientTypeExt clientTypeExt) {
		return ywBusinessMapper.selectXHHNum(clientTypeExt);
	}

	@Override
	public int countAllBusinessNum(ClientTypeExt clientTypeExt) {
		return ywBusinessMapper.countAllBusinessNum(clientTypeExt);
	}

	@Override
	public int countAllXHHNum(ClientTypeExt clientTypeExt) {
		return ywBusinessMapper.countAllXHHNum(clientTypeExt);
	}

	@Override
	public void updateOpenCardStatus(String busiId,SysUser user) {
		
		YwBusiness business=	ywBusinessMapper.selectByPrimaryKey(busiId);
		if(business!=null){
			String bbusiId=business.getId();
			String cusId=business.getCustomerId();
			if(business.getOpenCardStatus()==null || business.getOpenCardStatus()==2){
				business.setOpenCardStatus(OpenCardStatus.KA_DAN_YI_SHANG_CHUAN.getCode());
				ywBusinessMapper.updateByPrimaryKeySelective(business);
				
				//修改开卡信息表
				YwOpenCardHzicbc ywOpenCardHzicbc=new YwOpenCardHzicbc();
				ywOpenCardHzicbc.setBusiId(busiId);
				ywOpenCardHzicbc=ywOpenCardHzicbcMapper.selectRefined(ywOpenCardHzicbc);
				if(ywOpenCardHzicbc==null){
					ywOpenCardHzicbc=new YwOpenCardHzicbc();
					ywOpenCardHzicbc.initInsertData(user.getId(), user.getName());
					ywOpenCardHzicbc.setBusiId(bbusiId);
					ywOpenCardHzicbc.setCusId(cusId);
					ywOpenCardHzicbc.setOpenCardStatus(OpenCardStatus.KA_DAN_YI_SHANG_CHUAN.getCode());
					ywOpenCardHzicbcMapper.insert(ywOpenCardHzicbc);
				}else{
					ywOpenCardHzicbc.setOpenCardStatus(OpenCardStatus.KA_DAN_YI_SHANG_CHUAN.getCode());
					ywOpenCardHzicbcMapper.updateByPrimaryKeySelective(ywOpenCardHzicbc);
				}
				//暂时取消这个功能
//				YwOpenCardHzicbcSubmitInfo ywOpenCardHzicbcSubmitInfo=new YwOpenCardHzicbcSubmitInfo();
//				ywOpenCardHzicbcSubmitInfo.setDpStatus(DpStatus.NORMAL.getCode());
//				ywOpenCardHzicbcSubmitInfo.setBusiId(bbusiId);
//				ywOpenCardHzicbcSubmitInfo=ywOpenCardHzicbcSubmitInfoMapper.selectRefined(ywOpenCardHzicbcSubmitInfo);
//				if(ywOpenCardHzicbcSubmitInfo!=null){
//					ywOpenCardHzicbcSubmitInfo.initUpdateData(user.getId(), user.getName());
//					ywOpenCardHzicbcSubmitInfo.setAttSubmitTime(new Date());
//					ywOpenCardHzicbcSubmitInfo.setAttSubmitOperatorId(user.getId());
//					ywOpenCardHzicbcSubmitInfo.setAttSubmitOperator(user.getName());
//					ywOpenCardHzicbcSubmitInfoMapper.updateByPrimaryKeySelective(ywOpenCardHzicbcSubmitInfo);
//				}else{
//					ywOpenCardHzicbcSubmitInfo=new YwOpenCardHzicbcSubmitInfo();
//					ywOpenCardHzicbcSubmitInfo.setBusiId(bbusiId);
//					ywOpenCardHzicbcSubmitInfo.setCusId(cusId);
//					ywOpenCardHzicbcSubmitInfo.initInsertData(user.getId(), user.getName());
//					ywOpenCardHzicbcSubmitInfo.setAttSubmitTime(new Date());
//					ywOpenCardHzicbcSubmitInfo.setAttSubmitOperatorId(user.getId());
//					ywOpenCardHzicbcSubmitInfo.setAttSubmitOperator(user.getName());
//					ywOpenCardHzicbcSubmitInfoMapper.insert(ywOpenCardHzicbcSubmitInfo);
//				}
				
				YwOpenCardHzicbcLog ywOpenCardHzicbcLog=new YwOpenCardHzicbcLog();
				ywOpenCardHzicbcLog.setBusiId(bbusiId);
				ywOpenCardHzicbcLog.setCusId(cusId);
				ywOpenCardHzicbcLog.initInsertData(user.getId(), user.getName());
				ywOpenCardHzicbcLog.setLogType(1);
				ywOpenCardHzicbcLog.setRemarks(ywOpenCardHzicbc.getReasonBack());
				ywOpenCardHzicbcLog.setOpencardStatus(OpenCardStatus.KA_DAN_YI_SHANG_CHUAN.getCode().toString());
				ywOpenCardHzicbcLogMapper.insert(ywOpenCardHzicbcLog);
			}
			
		}
		
		
	}
}
